// src/api/picture.ts
import type { Picture, UploadPicture } from '@/types/picture'

// 模拟数据存储
let pictures: Picture[] = []
let idCounter = 1

// 生成唯一ID
const generateId = (): string => {
  return `pic_${Date.now()}_${idCounter++}`
}

// 模拟网络延迟
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))

export const pictureApi = {
  // 上传图片
  async uploadPicture(uploadData: UploadPicture): Promise<Picture> {
    await delay(1000) // 模拟上传延迟

    // 创建对象URL用于预览
    const objectUrl = URL.createObjectURL(uploadData.file)

    const newPicture: Picture = {
      id: generateId(),
      name: uploadData.name,
      size: uploadData.size,
      type: uploadData.type,
      url: objectUrl,
      uploadTime: new Date(),
      description: uploadData.description
    }

    // 保存到模拟数据库
    pictures.push(newPicture)

    return newPicture
  },

  // 获取图片列表
  async getPictures(): Promise<Picture[]> {
    await delay(500) // 模拟网络延迟
    return [...pictures].sort((a, b) => 
      new Date(b.uploadTime).getTime() - new Date(a.uploadTime).getTime()
    )
  },

  // 删除图片
  async deletePicture(id: string): Promise<void> {
    await delay(300)
    const index = pictures.findIndex(picture => picture.id === id)
    if (index !== -1) {
      // 释放对象URL
      URL.revokeObjectURL(pictures[index].url)
      pictures.splice(index, 1)
    }
  },

  // 根据ID获取图片
  async getPictureById(id: string): Promise<Picture | null> {
    await delay(200)
    return pictures.find(picture => picture.id === id) || null
  }
}